//! 链路接收池
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::future::pending;
use futures_util::future::select_all;
use unmp_link::prelude::{Connection, Listener};

pub struct Listeners {
    listeners: Vec<Listener>,
}
impl Listeners {
    pub fn new() -> Self {
        Self {
            listeners: Vec::new(),
        }
    }
    pub fn push(&mut self, listener: Listener) {
        log::info!("{:?} listening", listener.as_ref());
        self.listeners.push(listener);
    }
}
impl Listeners {
    /// 接收链路
    pub async fn accept(&mut self) -> Connection {
        loop {
            if self.listeners.is_empty() {
                pending::<()>().await;
            }
            let accept = self.listeners.iter_mut().map(|l| Box::pin(l.accept()));
            let (result, i, _) = select_all(accept).await;
            match result {
                Ok(conn) => return conn,
                Err(_) => {
                    let listener = self.listeners.swap_remove(i);
                    log::warn!("{:?} disconnected", listener.as_ref());
                }
            };
        }
    }
}
